<template>
  <el-dialog
    :modelValue="visible"
    @update:modelValue="$emit('update:visible', $event)"
    title="添加装箱单"
    width="70%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose">
    <div class="container-form">
      <div class="form-item">
        <div class="form-label">装箱单编号</div>
        <div class="form-content">
          <el-input v-model="form.packagingCode" placeholder="请输入装箱单编号">
            <template #append>
              <div style="display: flex; align-items: center; padding: 0 10px;">
                <el-switch v-model="autoGenerate" />
                <span style="margin-left: 5px; white-space: nowrap;">自动生成</span>
              </div>
            </template>
          </el-input>
        </div>
      </div>

      <div class="form-item">
        <div class="form-label required">装箱日期</div>
        <div class="form-content">
          <el-date-picker
            v-model="form.packagingName"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">销售订单编号</div>
        <div class="form-content">
          <el-input v-model="form.salesCode" placeholder="请输入销售订单编号" />
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">客户编码</div>
        <div class="form-content">
          <el-input v-model="form.clientCode" placeholder="请输入客户编码">
            <template #append>
              <el-button icon="Search" @click="openCustomerSelect" style="width: auto; padding: 0 10px;">
                <span style="margin-left: 5px;">搜索</span>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">客户名称</div>
        <div class="form-content">
          <el-input v-model="form.clientName" placeholder="请输入客户名称" />
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">发票编号</div>
        <div class="form-content">
          <el-input v-model="form.invoiceCode" placeholder="请输入发票编号" />
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">箱长度</div>
        <div class="form-content">
          <el-input v-model="form.boxLength" placeholder="请输入箱长度">
            <template #append>
              <el-select v-model="boxLengthUnit" placeholder="单位" style="width: 80px">
                <el-option
                  v-for="unit in ['公支', '英支', '匹', '捆', '层', '套', 'N.m']"
                  :key="unit"
                  :label="unit"
                  :value="unit"
                />
              </el-select>
            </template>
          </el-input>
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">箱宽度</div>
        <div class="form-content">
          <el-input v-model="form.boxWidth" placeholder="请输入箱宽度">
            <template #append>
              <span style="width: 30px; text-align: center;">cm</span>
            </template>
          </el-input>
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">箱高度</div>
        <div class="form-content">
          <el-input v-model="form.boxHeight" placeholder="请输入箱高度">
            <template #append>
              <span style="width: 30px; text-align: center;">cm</span>
            </template>
          </el-input>
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">净重</div>
        <div class="form-content">
          <el-input v-model="form.netweight" placeholder="请输入净重">
            <template #append>
              <el-select v-model="netweightUnit" placeholder="单位" style="width: 80px">
                <el-option
                  v-for="unit in ['公支', '英支', '匹', '捆', '层', '套', 'N.m']"
                  :key="unit"
                  :label="unit"
                  :value="unit"
                />
              </el-select>
            </template>
          </el-input>
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">毛重</div>
        <div class="form-content">
          <el-input v-model="form.grossweight" placeholder="请输入毛重">
            <template #append>
              <span style="width: 30px; text-align: center;">kg</span>
            </template>
          </el-input>
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">检查员名称</div>
        <div class="form-content">
          <el-input v-model="form.inspectorName" placeholder="请输入检查员名称" />
        </div>
      </div>

      <div class="form-item full-width">
        <div class="form-label">备注</div>
        <div class="form-content">
          <el-input
            v-model="form.descs"
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
          />
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSave">保 存</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </template>

    <!-- 客户选择组件 -->
    <customer-select
      v-if="customerSelectVisible"
      v-model:visible="customerSelectVisible"
      @select="handleCustomerSelect"
    />
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/api/http'
import CustomerSelect from './CustomerSelect.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 自动生成编号
const autoGenerate = ref(true)

// 单位选择
const boxLengthUnit = ref('公支')
const netweightUnit = ref('公支')

// 客户选择对话框
const customerSelectVisible = ref(false)

// 表单数据
const form = reactive({
  packagingCode: '',
  packagingName: new Date(),
  salesCode: '',
  clientCode: '',
  clientName: '',
  invoiceCode: '',
  boxLength: '',
  boxWidth: '',
  boxHeight: '',
  netweight: '',
  grossweight: '',
  inspectorName: '',
  descs: ''
})

// 生成装箱单号
const generatePackagingCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  
  return `PACK${year}${month}${day}${hours}${minutes}${seconds}`
}

// 监听自动生成开关
watch(autoGenerate, (newVal) => {
  if (newVal) {
    form.packagingCode = generatePackagingCode()
  }
})

// 打开客户选择对话框
const openCustomerSelect = () => {
  customerSelectVisible.value = true
}

// 处理客户选择
const handleCustomerSelect = (customer) => {
  form.clientCode = customer.custCode
  form.clientName = customer.custName
}

// 处理保存
const handleSave = async () => {
  // 如果启用了自动生成，确保生成最新的编号
  if (autoGenerate.value) {
    form.packagingCode = generatePackagingCode()
  }

  try {
    const res = await http.post('/api/Container/AddContainer', form)
    if (res.status === true) {
      ElMessage.success('添加成功')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(res.message || '添加失败')
    }
  } catch (error) {
    console.error('添加失败:', error)
    ElMessage.error('添加失败: ' + (error.message || '未知错误'))
  }
}

// 处理关闭
const handleClose = () => {
  // 重置表单数据
  Object.keys(form).forEach(key => {
    form[key] = key === 'packagingName' ? new Date() : ''
  })
  emit('update:visible', false)
}

// 组件挂载时，如果启用了自动生成，则生成编号
onMounted(() => {
  if (autoGenerate.value) {
    form.packagingCode = generatePackagingCode()
  }
})
</script>

<style scoped>
.container-form {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.form-item {
  position: relative;
}

.form-item.full-width {
  grid-column: span 3;
}

.form-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.form-label.required::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.form-content {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e4e7ed;
  padding: 15px 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #e4e7ed;
  padding: 15px 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 2px;
}

:deep(.el-textarea__inner) {
  border-radius: 2px;
}

:deep(.el-button) {
  border-radius: 2px;
}

:deep(.el-date-editor) {
  width: 100%;
}
</style> 